﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DomainModel;
using DomainModel.JSON;
using DomainModel.Entities;

namespace OrdersSystem.Controllers
{
    public class AdminController : Controller
    {
        private vUser CurrentUser;


        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            CurrentUser = Repositories.VUserRepository.GetUser(this.User.Identity.Name);
            InitViewData();
        }

        private void InitViewData()
        {
            if (this.ViewData["ManagerList"] == null)
            {

                string s = string.Empty;
                foreach (var u in Repositories.UserRepository.GetManagers())
                {
                    s += string.Format("{0}:{1};", u.UserID.ToString(), string.Format("{0} {1}.{2}.", u.Surname, u.Name[0], u.Patro[0]));
                }
                this.ViewData["ManagerList"] = s.TrimEnd(';');
            }
                                    
            if (this.ViewData["UserName"] == null)
            {
                this.ViewData["UserName"] = string.Format("{0} {1}.{2}.", CurrentUser.Surname, CurrentUser.Name[0], CurrentUser.Patro[0]);
                if (CurrentUser.IsClient)
                    this.ViewData["ManagerName"] = CurrentUser.ManagerName;
            }
        }


        public AdminController()
        {
           
        }
        //
        // GET: /Admin/

        public ActionResult ShowUsers()
        {
            if (!CurrentUser.IsAdmin)
                return RedirectToAction("List", "Orders");
            return View("Admin");
        }



        public ActionResult AddNewUser()
        {
            if (!CurrentUser.IsAdmin)
                return RedirectToAction("List", "Orders");


            User u = new User();
            u.Login = "Заполнить";
            u.Password = "123";
            u.rf_UserID = 1;
            u.rf_RoleID = 2;
            u.Organization = "Заполнить";
            u.FIO = "Новый Пользователь Системы";
            u.Phone = "Заполнить";
            u.Organization = "Заполнить";
            u.Email = "Заполнить@Email.ru";
            Repositories.UserRepository.Add(u);
            Repositories.UserRepository.Save();
            return View("Admin");
        }

        public JsonResult UserList_json(string sidx, string sord, int page, int rows)
        {
            List<vUser> ul = Repositories.VUserRepository.GetUsersOrdered().ToList();


            jsModelInstance js = new jsModelInstance(ul.Count,page,rows);
            int top = (page - 1) * rows;
            if (ul.Count - top < 0)
                js.rows = new jsModelRow[0];
            else
                js.rows = new jsModelRow[ul.Count - top];
           
            for (int i =top; i < ul.Count; i++)
            {
                js.rows[i - top] = new jsModelRow();
                js.rows[i - top].id = ul[i].UserID;
                js.rows[i - top].cell = new string[11];
                js.rows[i - top].cell[1] = ul[i].Organization;
                js.rows[i - top].cell[2] = string.Format("{0} {1} {2}", ul[i].Surname, ul[i].Name, ul[i].Patro);
                js.rows[i - top].cell[3] = ul[i].Phone;
                js.rows[i - top].cell[4] = ul[i].Email;
                js.rows[i - top].cell[5] = ul[i].ManagerName;
                js.rows[i - top].cell[6] = ul[i].Ratio.ToString();
                js.rows[i - top].cell[7] = ul[i].isFinVisible ? "Да" : "Нет";
                js.rows[i - top].cell[8] = ul[i].RoleName;
                js.rows[i - top].cell[9] = ul[i].Login;
                js.rows[i - top].cell[10] = ul[i].Password;
            }

            js.records = ul.Count;            

            
               
            return Json(js, JsonRequestBehavior.AllowGet);
        }


        public EmptyResult UserListSave(int id, string oper)
        {
            if (oper.ToLower() == "del")
            {
                if (id == 1)
                    return new EmptyResult();
                if (Repositories.UserRepository.GetClientsCountForManager(id)>0)
                    return new EmptyResult();

                User u = Repositories.UserRepository.GetUser(id);
                
                Repositories.UserRepository.Delete(u);
                Repositories.UserRepository.Save();
            }
            else
            {
                User u = Repositories.UserRepository.GetUser(id);
                if (id != 1) 
                  
                u.Organization = this.Request["Организация"];
                u.FIO = this.Request["ФИО пользователя"];
                u.Phone = this.Request["Телефон"];
                u.Email = this.Request["E-Mail"];
                if (id != 1)
                    u.rf_UserID = Convert.ToInt32(this.Request["Менеджер"]);
                if (id != 1)
                    u.rf_RoleID = Convert.ToInt32(this.Request["Роль"]);
                if (id != 1)
                    u.Login = this.Request["Логин"];
                u.Password = this.Request["Пароль"];
                u.Ratio = Convert.ToDecimal(this.Request["Коэффициент"]);
                u.isFinVisible = this.Request["FinVisible"].ToLower()=="да";
                Repositories.UserRepository.Save();
            }
            return new EmptyResult();
        }

    }
}
